Skip to content

Gorm

Tags
Golang
Gorm
Words count
423 字
Reading time
2 分钟

连接数据库

MySQL

go
type Project struct{} 

func connect() {
	dsn := "root:password@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
		
	db, err := gorm.Open(mysql.New(mysql.Config{ // MySQL 配置
		DSN: dsn,
		DefaultStringSize: 256, // string 类型字段默认长度
		DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
		DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
		DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列,
		SkipInitializeWithVersion: false, // 跳过根据当前 MySQL 版本自动配置
	}), &gorm.Config{ // gorm 配置
		SkipDefaultTransaction: true, // 禁用默认事务
		NamingStrategy: schema.NamingStrategy{
		TablePrefix: "t_", // 表前缀
		SingularTable: true, // 是否使用复数表名
		NoLowerCase: true, // 是否转成小写「snake_casing」
		NameReplacer: strings.NewReplacer("ID", "id"), // 命名策略
		},
		Logger: logger.New(
			log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
			logger.Config{
				SlowThreshold: time.Second, // 慢 SQL 阈值
				LogLevel: logger.Info, // 日志级别
				IgnoreRecordNotFoundError: true, // 忽略 ErrRecordNotFound 错误
				ParameterizedQueries: true, // 使用参数化查
				Colorful: true, // 彩色打印
			},
		),
		NowFunc: func() time.Time { // 更改创建时间使用的函数
		return time.Now().Local()
		},
		DryRun: true, // 生成 SQL 但不执行,用户准备或测试 SQL
		PrepareStmt: true, // 创建执行过的 SQL 对应的 prepared statement 并缓存,以提高后续效率
		AllowGlobalUpdate: true, // 全局更新/删除
		DisableAutomaticPing: false, // 禁用初始化后自动 ping
		DisableForeignKeyConstraintWhenMigrating: true, // 禁用自动创建外键约束
	})
	
	if err != nil {
		panic("failed to connect database")
	}
	
	sqlDB, err := db.DB()
	if err != nil {
		panic("failed to connect database")
	}  
	
	sqlDB.SetMaxIdleConns(10) // 设置空闲连接池中连接的最大数量
	sqlDB.SetMaxOpenConns(100) // 设置打开数据库连接的最大数量
	sqlDB.SetConnMaxLifetime(time.Hour) // 设置连接可复用的最大时间
	
	db.AutoMigrate(&Project{}) // 迁移 schema

}